package org.ucas.faker.web.fetcher.op;

import javafx.util.Pair;
import org.ucas.faker.web.fetcher.cond.FetchCond;
import org.ucas.faker.web.fetcher.meta.ColumnField;
import org.ucas.faker.web.fetcher.meta.JoinTable;
import org.ucas.faker.web.fetcher.meta.Table;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Join implements Serializable{

  public Table left;

  public Table right;

  public FetchCond cond;

  String op = "INNER JOIN";

  public Join(Table left, Table right, FetchCond cond) {
    this.left = left;
    this.right = right;
    this.cond = cond;
  }

  public Join() {
  }

  public String sql() {
    assert(left != null);
    if(cond == null ) {
      return left.sql() + "," +(right == null? "" : right.sql());
    }
    String res = left.sql() + " " + op + " " + right.sql() + " ON ";
    res += cond.sql();

    return res;
  }

  public Join find(Table table) {
    if(this.right != null && this.right.equals(table)) return this;
    if(this.left == null) return null;

    if(left instanceof JoinTable) {
      JoinTable sub = (JoinTable) left;
      return sub.join == null? null:sub.join.find(table);
    } else
      return this.left.equals(table)? this : null;
  }

  public Join mostLeft() {
    if(left == null || !(left instanceof JoinTable)) return this;
    Join join = ((JoinTable) left).join;
    return join.mostLeft();
  }

  public List<Table> tables() {
    List<Table> res = new ArrayList<>();
    if(right != null) res.add(right);
    if(left != null && left instanceof JoinTable) {
      res.addAll(((JoinTable) left).join.tables());
    } else if(left != null)
      res.add(left);
    return res;
  }

  public void replace(Table src, Table dst) {
    if(left != null && left.equals(src)) left = src;
    if(right != null && right.equals(src)) right = src;
    if(cond != null) cond.replace(src,dst);

    if(left instanceof JoinTable) {
      JoinTable tmp = (JoinTable) left;
      tmp.join.replace(src,dst);
    }
  }
}
